package com.work.yshop.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 用户数据内容提供者
 * 用于存储用户的足迹、收藏、购物车和订单数据
 */
public class UserDataProvider extends ContentProvider {

    // 数据库名
    private static final String DATABASE_NAME = "user_data.db";
    // 数据库版本
    private static final int DATABASE_VERSION = 1;
    
    // 表名
    public static final String TABLE_HISTORY = "product_history";
    public static final String TABLE_FAVORITES = "product_favorites";
    public static final String TABLE_CART = "shopping_cart";
    public static final String TABLE_ORDERS = "orders";
    public static final String TABLE_ORDER_ITEMS = "order_items";
    
    // 授权URI
    public static final String AUTHORITY = "com.work.yshop.provider.userdata";
    
    // 内容URI
    public static final Uri HISTORY_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_HISTORY);
    public static final Uri FAVORITES_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_FAVORITES);
    public static final Uri CART_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_CART);
    public static final Uri ORDERS_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_ORDERS);
    public static final Uri ORDER_ITEMS_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_ORDER_ITEMS);
    
    // URI匹配码
    private static final int HISTORY = 1;
    private static final int HISTORY_ID = 2;
    private static final int FAVORITES = 3;
    private static final int FAVORITES_ID = 4;
    private static final int CART = 5;
    private static final int CART_ID = 6;
    private static final int ORDERS = 7;
    private static final int ORDER_ID = 8;
    private static final int ORDER_ITEMS = 9;
    private static final int ORDER_ITEM_ID = 10;
    
    // URI匹配器
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
    static {
        sUriMatcher.addURI(AUTHORITY, TABLE_HISTORY, HISTORY);
        sUriMatcher.addURI(AUTHORITY, TABLE_HISTORY + "/#", HISTORY_ID);
        sUriMatcher.addURI(AUTHORITY, TABLE_FAVORITES, FAVORITES);
        sUriMatcher.addURI(AUTHORITY, TABLE_FAVORITES + "/#", FAVORITES_ID);
        sUriMatcher.addURI(AUTHORITY, TABLE_CART, CART);
        sUriMatcher.addURI(AUTHORITY, TABLE_CART + "/#", CART_ID);
        sUriMatcher.addURI(AUTHORITY, TABLE_ORDERS, ORDERS);
        sUriMatcher.addURI(AUTHORITY, TABLE_ORDERS + "/#", ORDER_ID);
        sUriMatcher.addURI(AUTHORITY, TABLE_ORDER_ITEMS, ORDER_ITEMS);
        sUriMatcher.addURI(AUTHORITY, TABLE_ORDER_ITEMS + "/#", ORDER_ITEM_ID);
    }
    
    // 数据库助手
    private DatabaseHelper mDbHelper;
    
    /**
     * 数据库助手类
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {
        
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        
        @Override
        public void onCreate(SQLiteDatabase db) {
            // 创建浏览历史表
            db.execSQL("CREATE TABLE " + TABLE_HISTORY + " ("
                    + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "product_id INTEGER NOT NULL,"
                    + "user_id INTEGER NOT NULL,"
                    + "view_time INTEGER NOT NULL,"
                    + "UNIQUE(product_id, user_id) ON CONFLICT REPLACE"
                    + ");");
            
            // 创建收藏表
            db.execSQL("CREATE TABLE " + TABLE_FAVORITES + " ("
                    + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "product_id INTEGER NOT NULL,"
                    + "user_id INTEGER NOT NULL,"
                    + "favorite_time INTEGER NOT NULL,"
                    + "UNIQUE(product_id, user_id) ON CONFLICT REPLACE"
                    + ");");
            
            // 创建购物车表
            db.execSQL("CREATE TABLE " + TABLE_CART + " ("
                    + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "product_id INTEGER NOT NULL,"
                    + "user_id INTEGER NOT NULL,"
                    + "quantity INTEGER NOT NULL,"
                    + "selected INTEGER NOT NULL DEFAULT 1,"
                    + "add_time INTEGER NOT NULL,"
                    + "UNIQUE(product_id, user_id) ON CONFLICT REPLACE"
                    + ");");
            
            // 创建订单表
            db.execSQL("CREATE TABLE " + TABLE_ORDERS + " ("
                    + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "order_number TEXT NOT NULL UNIQUE,"
                    + "user_id INTEGER NOT NULL,"
                    + "buyer_name TEXT NOT NULL,"
                    + "order_time TEXT NOT NULL,"
                    + "total_amount REAL NOT NULL,"
                    + "status INTEGER NOT NULL,"
                    + "address TEXT,"
                    + "phone TEXT"
                    + ");");
            
            // 创建订单项表
            db.execSQL("CREATE TABLE " + TABLE_ORDER_ITEMS + " ("
                    + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "order_id INTEGER NOT NULL,"
                    + "product_id INTEGER NOT NULL,"
                    + "product_name TEXT NOT NULL,"
                    + "price REAL NOT NULL,"
                    + "quantity INTEGER NOT NULL,"
                    + "image_url TEXT,"
                    + "FOREIGN KEY(order_id) REFERENCES " + TABLE_ORDERS + "(_id) ON DELETE CASCADE"
                    + ");");
        }
        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // 升级数据库
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_CART);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ORDER_ITEMS);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ORDERS);
            onCreate(db);
        }
    }
    
    @Override
    public boolean onCreate() {
        mDbHelper = new DatabaseHelper(getContext());
        return true;
    }
    
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,
                        @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        Cursor cursor;
        
        switch (sUriMatcher.match(uri)) {
            case HISTORY:
                cursor = db.query(TABLE_HISTORY, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case HISTORY_ID:
                long historyId = ContentUris.parseId(uri);
                cursor = db.query(TABLE_HISTORY, projection, "_id = ?",
                        new String[]{String.valueOf(historyId)}, null, null, sortOrder);
                break;
            case FAVORITES:
                cursor = db.query(TABLE_FAVORITES, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case FAVORITES_ID:
                long favoriteId = ContentUris.parseId(uri);
                cursor = db.query(TABLE_FAVORITES, projection, "_id = ?",
                        new String[]{String.valueOf(favoriteId)}, null, null, sortOrder);
                break;
            case CART:
                cursor = db.query(TABLE_CART, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case CART_ID:
                long cartId = ContentUris.parseId(uri);
                cursor = db.query(TABLE_CART, projection, "_id = ?",
                        new String[]{String.valueOf(cartId)}, null, null, sortOrder);
                break;
            case ORDERS:
                cursor = db.query(TABLE_ORDERS, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case ORDER_ID:
                long orderId = ContentUris.parseId(uri);
                cursor = db.query(TABLE_ORDERS, projection, "_id = ?",
                        new String[]{String.valueOf(orderId)}, null, null, sortOrder);
                break;
            case ORDER_ITEMS:
                cursor = db.query(TABLE_ORDER_ITEMS, projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case ORDER_ITEM_ID:
                long orderItemId = ContentUris.parseId(uri);
                cursor = db.query(TABLE_ORDER_ITEMS, projection, "_id = ?",
                        new String[]{String.valueOf(orderItemId)}, null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        // 设置内容观察者
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }
    
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case HISTORY:
                return "vnd.android.cursor.dir/vnd.com.work.yshop.history";
            case HISTORY_ID:
                return "vnd.android.cursor.item/vnd.com.work.yshop.history";
            case FAVORITES:
                return "vnd.android.cursor.dir/vnd.com.work.yshop.favorites";
            case FAVORITES_ID:
                return "vnd.android.cursor.item/vnd.com.work.yshop.favorites";
            case CART:
                return "vnd.android.cursor.dir/vnd.com.work.yshop.cart";
            case CART_ID:
                return "vnd.android.cursor.item/vnd.com.work.yshop.cart";
            case ORDERS:
                return "vnd.android.cursor.dir/vnd.com.work.yshop.orders";
            case ORDER_ID:
                return "vnd.android.cursor.item/vnd.com.work.yshop.orders";
            case ORDER_ITEMS:
                return "vnd.android.cursor.dir/vnd.com.work.yshop.order_items";
            case ORDER_ITEM_ID:
                return "vnd.android.cursor.item/vnd.com.work.yshop.order_items";
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
    }
    
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        long id;
        Uri contentUri;
        
        switch (sUriMatcher.match(uri)) {
            case HISTORY:
                id = db.insert(TABLE_HISTORY, null, values);
                contentUri = HISTORY_URI;
                break;
            case FAVORITES:
                id = db.insert(TABLE_FAVORITES, null, values);
                contentUri = FAVORITES_URI;
                break;
            case CART:
                id = db.insert(TABLE_CART, null, values);
                contentUri = CART_URI;
                break;
            case ORDERS:
                id = db.insert(TABLE_ORDERS, null, values);
                contentUri = ORDERS_URI;
                break;
            case ORDER_ITEMS:
                id = db.insert(TABLE_ORDER_ITEMS, null, values);
                contentUri = ORDER_ITEMS_URI;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        if (id > 0) {
            Uri newUri = ContentUris.withAppendedId(contentUri, id);
            getContext().getContentResolver().notifyChange(newUri, null);
            return newUri;
        }
        
        return null;
    }
    
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        int count;
        Uri notifyUri;
        
        switch (sUriMatcher.match(uri)) {
            case HISTORY:
                count = db.delete(TABLE_HISTORY, selection, selectionArgs);
                notifyUri = HISTORY_URI;
                break;
            case HISTORY_ID:
                long historyId = ContentUris.parseId(uri);
                count = db.delete(TABLE_HISTORY, "_id = ?", new String[]{String.valueOf(historyId)});
                notifyUri = HISTORY_URI;
                break;
            case FAVORITES:
                count = db.delete(TABLE_FAVORITES, selection, selectionArgs);
                notifyUri = FAVORITES_URI;
                break;
            case FAVORITES_ID:
                long favoriteId = ContentUris.parseId(uri);
                count = db.delete(TABLE_FAVORITES, "_id = ?", new String[]{String.valueOf(favoriteId)});
                notifyUri = FAVORITES_URI;
                break;
            case CART:
                count = db.delete(TABLE_CART, selection, selectionArgs);
                notifyUri = CART_URI;
                break;
            case CART_ID:
                long cartId = ContentUris.parseId(uri);
                count = db.delete(TABLE_CART, "_id = ?", new String[]{String.valueOf(cartId)});
                notifyUri = CART_URI;
                break;
            case ORDERS:
                count = db.delete(TABLE_ORDERS, selection, selectionArgs);
                notifyUri = ORDERS_URI;
                break;
            case ORDER_ID:
                long orderId = ContentUris.parseId(uri);
                count = db.delete(TABLE_ORDERS, "_id = ?", new String[]{String.valueOf(orderId)});
                notifyUri = ORDERS_URI;
                break;
            case ORDER_ITEMS:
                count = db.delete(TABLE_ORDER_ITEMS, selection, selectionArgs);
                notifyUri = ORDER_ITEMS_URI;
                break;
            case ORDER_ITEM_ID:
                long orderItemId = ContentUris.parseId(uri);
                count = db.delete(TABLE_ORDER_ITEMS, "_id = ?", new String[]{String.valueOf(orderItemId)});
                notifyUri = ORDER_ITEMS_URI;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        if (count > 0) {
            getContext().getContentResolver().notifyChange(notifyUri, null);
        }
        
        return count;
    }
    
    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection,
                      @Nullable String[] selectionArgs) {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        int count;
        Uri notifyUri;
        
        switch (sUriMatcher.match(uri)) {
            case HISTORY:
                count = db.update(TABLE_HISTORY, values, selection, selectionArgs);
                notifyUri = HISTORY_URI;
                break;
            case HISTORY_ID:
                long historyId = ContentUris.parseId(uri);
                count = db.update(TABLE_HISTORY, values, "_id = ?", new String[]{String.valueOf(historyId)});
                notifyUri = HISTORY_URI;
                break;
            case FAVORITES:
                count = db.update(TABLE_FAVORITES, values, selection, selectionArgs);
                notifyUri = FAVORITES_URI;
                break;
            case FAVORITES_ID:
                long favoriteId = ContentUris.parseId(uri);
                count = db.update(TABLE_FAVORITES, values, "_id = ?", new String[]{String.valueOf(favoriteId)});
                notifyUri = FAVORITES_URI;
                break;
            case CART:
                count = db.update(TABLE_CART, values, selection, selectionArgs);
                notifyUri = CART_URI;
                break;
            case CART_ID:
                long cartId = ContentUris.parseId(uri);
                count = db.update(TABLE_CART, values, "_id = ?", new String[]{String.valueOf(cartId)});
                notifyUri = CART_URI;
                break;
            case ORDERS:
                count = db.update(TABLE_ORDERS, values, selection, selectionArgs);
                notifyUri = ORDERS_URI;
                break;
            case ORDER_ID:
                long orderId = ContentUris.parseId(uri);
                count = db.update(TABLE_ORDERS, values, "_id = ?", new String[]{String.valueOf(orderId)});
                notifyUri = ORDERS_URI;
                break;
            case ORDER_ITEMS:
                count = db.update(TABLE_ORDER_ITEMS, values, selection, selectionArgs);
                notifyUri = ORDER_ITEMS_URI;
                break;
            case ORDER_ITEM_ID:
                long orderItemId = ContentUris.parseId(uri);
                count = db.update(TABLE_ORDER_ITEMS, values, "_id = ?", new String[]{String.valueOf(orderItemId)});
                notifyUri = ORDER_ITEMS_URI;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        if (count > 0) {
            getContext().getContentResolver().notifyChange(notifyUri, null);
        }
        
        return count;
    }
} 